﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Licensed MIT: http://www.opensource.org/licenses/mit-license.php
using System;
using System.Collections.Generic;
using System.Net.Mail;
using System.Web.Configuration;
using System.Net.Configuration;
using System.Web.Security;

namespace DNA.Mvc.Notification
{
    /// <summary>
    /// Present the email subscription sender base class.
    /// </summary>
    public abstract class MailSubscriptionSender : SubscriptionSenderBase
    {
        /// <summary>
        /// Gets/Sets the prefix text on email subject.
        /// </summary>
        public virtual string SubjectPrefix { get; set; }

        public virtual string SenderTitle { get; set; }

        protected virtual void OnPopuplateMailMessage(MailMessage message) { }

        public override void Send(string[] subscribers, IMessage message)
        {
            var webConfig = WebConfigurationManager.OpenWebConfiguration("~/web.config");
            var smtp = webConfig.GetSection("system.net/mailSettings/smtp") as SmtpSection;
            if (smtp != null)
            {
                if (smtp.Network != null)
                {
                    var address = new List<string>();
                    foreach (var user in subscribers)
                    {
                        var _member = Membership.GetUser(user);
                        if (_member != null)
                            address.Add(_member.Email);
                    }

                    var mail = new MailMessage();

                    if (!string.IsNullOrEmpty(smtp.From))
                    {
                        if (string.IsNullOrEmpty(SenderTitle))
                            mail.From = new MailAddress(smtp.From);
                        else
                            mail.From = new MailAddress(smtp.From, SenderTitle);
                    }

                    mail.Bcc.Add(string.Join(",", address.ToArray()));
                    mail.Subject = string.IsNullOrEmpty(SubjectPrefix) ? message.Title : SubjectPrefix + message.Title;
                    mail.Body = message.Content;
                   
                    if (!string.IsNullOrEmpty(message.ContentType))
                        mail.IsBodyHtml = message.ContentType.Equals("text/html", StringComparison.OrdinalIgnoreCase);

                    if (!string.IsNullOrEmpty(message.Encoding))
                    {
                        var encoding = System.Text.Encoding.GetEncoding(message.Encoding);
                        mail.BodyEncoding = encoding;
                        mail.SubjectEncoding = encoding;
                    }

                    OnPopuplateMailMessage(mail);

                    var smtpClient = new SmtpClient();
                    smtpClient.SendAsync(mail, null);
                }
            }
        }
    }
}
